<template>
  <div class="info">
    <van-form @submit="onSubmit" :model-value="formData" class="table-form">
      <van-field
        v-model="rusticName"
        is-link
        readonly
        name="rusticName"
        label="乡村"
        placeholder="点击选择关联乡村"
        :rules="[{ required: true, message: '请选择关联乡村' }]"
        @click="showList = true"
      />
      <van-field
        v-model="formData.name"
        name="name"
        label="攻略名称"
        placeholder="攻略名称"
        :rules="[{ required: true, message: '请填写攻略名称' }]"
      />
      <van-field name="cover" label="封面">
        <template #input>
          <van-uploader
            multiple
            :max-count="1"
            v-model="coverList"
            :max-size="4000 * 1024"
            @oversize="onOversize"
            :after-read="afterReadCover"
          />
        </template>
      </van-field>
      <van-field name="images" label="轮播图">
        <template #input>
          <van-uploader multiple :max-count="4" v-model="imagesList" :max-size="4000 * 1024" @oversize="onOversize" />
        </template>
      </van-field>
      <van-field
        class="introduce-cell"
        v-model="formData.introduce"
        name="introduce"
        placeholder="请填写介绍，旅游攻略等信息"
        rows="3"
        autosize
        type="textarea"
        :rules="[{ required: true, message: '请填写介绍' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
    <!-- 乡村列表 -->
    <van-popup v-model:show="showList" position="bottom" style="max-height: 90%; padding-top: 4px">
      <div class="rustic-list">
        <div class="intro-header">
          <var-input placeholder="搜索乡村" clearable v-model="query" enterkeyhint="done" @blur="search" @change="search">
            <template #append-icon>
              <var-icon class="append-icon" name="magnify" />
            </template>
          </var-input>
        </div>
        <var-tabs-items v-model:active="active">
          <var-tab-item name="rustic">
            <div class="btn-wrap">
              <var-list finished-text="没有更多了" error-text="出错了出错了" :finished="finished" v-model:loading="loading" @load="load">
                <var-cell :key="item.id" v-for="item in rusticList">
                  <var-card
                    :title="item.name"
                    :subtitle="'简介: ' + item.briefIntro"
                    :description="item.address"
                    :src="getFileHttpUrl(item.cover)"
                    layout="row"
                    @click="rusticClick(item.id, item.name)"
                  />
                </var-cell>
              </var-list>
            </div>
          </var-tab-item>
        </var-tabs-items>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
  import { getFileHttpUrl } from '@/utils/urlUtils';
  import type { Dayjs } from 'dayjs';
  import { getRusticList } from '@/api/rustic';
  import { message } from 'ant-design-vue';
  import { showToast } from 'vant';
  import { uploadFile } from '@/api/comment';
  import { addTravelPlan } from '@/api/travelPlan';

  const router = useRouter();
  const showList = ref(false);
  const active = ref('rustic');
  const query = ref('');
  const list = ref([]);
  let current = 1;
  const loading = ref(false);
  const rusticName = ref('');
  const coverList = ref<{ url: string }[]>([]);
  const imagesList = ref([]);

  const formData = ref<API.CreateTravelPlanData>({
    rusticId: null,
    name: '',
    cover: '',
    images: '',
    introduce: '',
    status: 1,
  });

  const onSubmit = async () => {
    // 上传轮播图
    const tempList = ref<{ url: string }[]>([]);
    const uploadPromises = imagesList.value.map(async (item: any) => {
      try {
        // 此时可以自行将文件上传至服务器
        const coverFormData = new FormData();
        coverFormData.append('file', item.file);
        const res = await uploadFile(coverFormData);
        if (res.code === 0) {
          // 赋值
          tempList.value.push({ url: res.data.url });
        }
      } catch (error) {
        console.error('上传轮播图时发生错误：', error);
      }
    });
    // 等待所有异步上传操作完成
    await Promise.all(uploadPromises);
    formData.value.images = tempList.value
      .filter((item) => item.url) // 确保每个元素都有 url 属性且不为空
      .map((item) => item.url)
      .join(',');
    const res = await addTravelPlan({ ...formData.value });
    if (res) {
      message.success(res?.msg);
      router.go(-1);
    }
  };

  const finished = ref(false);
  const rusticList = ref<
    {
      id: number;
      name: string;
      briefIntro: string;
      address: string;
      detailedAddress: string;
      cover: string;
      publishTime: Dayjs;
      updateTime: string;
      createTime: string;
      likeCount: number;
      collectionCount: number;
      browseCount: number;
      collection: boolean;
      like: boolean;
      rusticName: string;

      feature: string;
      creator: string;
    }[]
  >([]);

  /**
   * 图片上传
   */
  const onOversize = () => {
    showToast('图片大小不能超过 4Mb');
  };
  const afterReadCover = async (file: any) => {
    // 此时可以自行将文件上传至服务器
    const coverFormData = new FormData();
    coverFormData.append('file', file.file);
    const res = await uploadFile(coverFormData);
    if (res) {
      if (res.code === 0) {
        const url = res.data.url;
        // 赋值
        formData.value.cover = url;
        coverList.value = [];
        coverList.value.push({ url: getFileHttpUrl(url) });
        return res.data.url;
      }
    }
  };
  const getList = async () => {
    const res = await getRusticList({ name: query.value, current: current, size: 10 });

    if (res) {
      current = res.data.current + 1;
      if (res.data.total == 0) {
        finished.value = true;
        return;
      }
      setListData(res.data.current > 1 ? [...list.value, ...res.data.records] : (res.data.records as any[]));
      rusticList.value = list.value.map(
        (item: {
          id: number;
          name: string;
          briefIntro: string;
          address: string;
          detailedAddress: string;
          cover: string;
          publishTime: Dayjs;
          updateTime: string;
          createTime: string;
          likeCount: number;
          collectionCount: number;
          browseCount: number;
          collection: boolean;
          like: boolean;
          rusticName: string;
          feature: string;
          creator: string;
        }) => ({
          id: item.id,
          name: item.name,
          briefIntro: item.briefIntro,
          address: item.address,
          detailedAddress: item.detailedAddress,
          cover: item.cover,
          publishTime: item.publishTime,
          updateTime: item.updateTime,
          createTime: item.createTime,
          likeCount: item.likeCount,
          collectionCount: item.collectionCount,
          browseCount: item.browseCount,
          collection: item.collection,
          like: item.like,
          rusticName: item.rusticName,
          feature: item.feature,
          creator: item.creator,
        }),
      );
      // 将映射后的新数据追加到 rusticList 中
      // rusticList.value.push(...rusticListTemp.value);
      if (rusticList.value.length == 0) {
        finished.value = true;
      }
      return res.data.record;
    }
  };
  const setListData = (data: any) => {
    list.value = data;
  };
  const load = () => {
    setTimeout(() => {
      getList();
      loading.value = false;
    }, 1000);
  };

  /**
   * 查询的时候清空原来的数据
   */
  const search = () => {
    loading.value = true;
    list.value = [];
    current = 1;
    load();
    // 若是没有数据则清空原来的数据
    if (list.value.length == 0) {
      rusticList.value = [];
    }
    // console.info('失焦后数据 ===> ', list);
  };
  /**
   * 乡村卡片点击添加数据
   */
  const rusticClick = (id: number, name: string) => {
    formData.value.rusticId = id;
    rusticName.value = name;
    showList.value = false;
  };
</script>

<style lang="scss" scoped>
  .nut-swiper-item {
    line-height: 500px;
    img {
      width: 100%;
      height: 100%;
    }
  }

  .info {
    padding: 20px;
    .table-form {
      .introduce-cell {
        margin-top: 30px;
      }
    }
  }
  .rustic-list {
    background: #e2e8ef;
    .intro-header {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 20px;
      font-size: 16px;
      width: 100%;
    }
  }
</style>
